<template>
  <div class="execution">
    <basic-container>
      <avue-crud ref="crud"
                 :page="page"
                 :data="tableData"
                 :table-loading="tableLoading"
                 :option="tableOption"
                 v-model="form"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @search-change="searchChange"
                 @refresh-change="refreshChange"
                 @row-update="handleUpdate"
                 @row-save="handleSave"
                 @row-del="rowDel">
        <template slot="menuLeft">
          <el-button type="primary"
                     @click="handleAdd"
                     size="small">新 增
          </el-button>
          <br/><br/>
        </template>
        <template slot-scope="scope"
                  slot="menu">
          <!--          <el-button type="text"-->
          <!--                     icon="el-icon-check"-->
          <!--                     size="small"-->
          <!--                     plain-->
          <!--                     @click="handleOpenSerTypeDialog(scope.row,scope.index)">服务类型-->
          <!--          </el-button>-->
          <el-button type="text"
                     icon="el-icon-check"
                     size="small"
                     plain
                     @click="handleGeneratingCode(scope.row,scope.index)">生成优惠券二维码
          </el-button>
          <el-button type="text"
                     icon="el-icon-check"
                     size="small"
                     plain
                     @click="handleEdit(scope.row,scope.index)">编辑
          </el-button>
          <el-button type="text"
                     icon="el-icon-delete"
                     size="small"
                     plain
                     @click="handleDel(scope.row,scope.index)">删除
          </el-button>
        </template>
        <template slot="couponCodePath" slot-scope="scope">
          <img v-if="scope.row.couponCodePath" height="150" width="150" :src="scope.row.couponCodePath">
        </template>
        <template slot="shopHoursForm"
                  slot-scope="scope">
          <el-time-picker
            is-range
            arrow-control
            v-model="form.shopHours"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围">
          </el-time-picker>
        </template>
        <template slot="mapForm"
                  slot-scope="scope">
          <tx-map ref="mapForm" @location="getLocation" :lat="Number(form.shopLatitude)"
                  :lng="Number(form.shopLongitude)"></tx-map>
        </template>
        <template slot="serviceTypeIdForm"
                  slot-scope="scope">
          <!--          <el-checkbox-group :min="1" v-model="typeIdListChecked" @change="handleCheckedTypeIdChange">-->
          <!--            <el-checkbox v-for="item in typeIds" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>-->
          <!--          </el-checkbox-group>-->
          <el-select v-model="form.serviceTypeId" placeholder="请选择">
            <el-option
              v-for="item in typeIds"
              :key="Number(item.id)"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </avue-crud>
    </basic-container>

    <!--服务类型弹窗-->
    <el-dialog title="服务类型" :visible.sync="serTypeDialogVisible">
      <div>
        <el-checkbox-group :min="1" v-model="typeIdListChecked" @change="handleCheckedTypeIdChange">
          <el-checkbox v-for="item in typeIds" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </div>
    </el-dialog>

    <el-dialog title="商场管理用户" :visible.sync="merUserDialogVisible">
      <div>
        <el-checkbox-group v-model="merUserListChecked" @change="handleCheckedMerUserChange">
          <el-checkbox v-for="item in merUserList" :label="item.userId" :key="item.userId">{{item.username}}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchList, getObj, addObj, putObj, delObj} from '@/api/shop/shops'
  import {addShopUserObj} from '@/api/shop/shopuser'
  import {saveShopSerTypes} from '@/api/shop/shopservicestype'
  import {allMerServiceTypes} from '@/api/merchantservices/merservicestype'
  import {generatingCouponCode} from '@/api/marketing/coupon'
  import {getShopSerTypeObjByShopId} from '@/api/shop/shopservicestype'
  import {tableOption} from '@/const/crud/shop/shops'
  import TxMap from '@/components/map/map'

  export default {
    name: 'shops',
    components: {
      TxMap
    },
    data() {
      return {
        serTypeDialogVisible: false,
        merUserDialogVisible: false,
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        form: {
          radiationRange: 0.00,
          shopLatitude: '35.792945',
          shopLongitude: '112.928676',
          serviceTypeId: ''
        },
        typeIdListChecked: [],
        merUserListChecked: [],
        typeIds: [],
        merUserList: [],
        currentShopId: '',
        location: {},
        shopId: this.$store.state.user.shopId
        // shopLatitude: 35.792945,
        // shopLongitude: 112.928676
      }
    },
    mounted: function () {
      this.getList(this.page, {'id': this.shopId})
    },
    // computed: {
    //   ...mapGetters(['permissions'])
    // },
    methods: {
      getList(page, params) {
        this.tableLoading = true
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
        })
      },
      /**
       * @title 打开新增窗口
       * @detail 调用crud的handleadd方法即可
       *
       **/
      handleAdd: function () {
        allMerServiceTypes()
          .then(res => {
            this.typeIds = res.data.data
          })
        this.$refs.crud.rowAdd()
        this.$nextTick(() => {
          if (!this.form.shopLatitude) {
            this.form.shopLatitude = 35.792945
          }
          if (!this.form.shopLongitude) {
            this.form.shopLongitude = 112.928676
          }
          this.$refs.mapForm.init(this.form.shopLatitude, this.form.shopLongitude)
        })
      },
      handleEdit(row, index) {
        let _this = this;
        allMerServiceTypes()
          .then(res => {
            _this.typeIds = res.data.data
          })

        getObj(row.id).then(res => {
          row.shopHours = [
            new Date(Number(res.data.data.openingHours)),
            new Date(Number(res.data.data.closingHours))
          ]
          // this.shopLatitude = Number(res.data.data.shopLatitude)
          // this.shopLongitude = Number(res.data.data.shopLongitude)
          this.$refs.crud.rowEdit(row, index)
          this.$nextTick(() => {
            if (!row.shopLatitude || row.shopLatitude === 'NaN' || row.shopLatitude === 'undefined') {
              this.form.shopLatitude = 35.792945
            }
            if (!row.shopLongitude || row.shopLongitude === 'NaN' || row.shopLongitude === 'undefined') {
              this.form.shopLongitude = 112.928676
            }
            this.$refs.mapForm.init(this.form.shopLatitude, this.form.shopLongitude)
          })

        })

      },
      handleDel(row, index) {
        this.$refs.crud.rowDel(row, index)
      },
      rowDel: function (row, index) {
        var _this = this
        this.$confirm('是否确认删除ID为' + row.id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.id)
        }).then(data => {
          _this.tableData.splice(index, 1)
          _this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getList(this.page, {'id': this.shopId})
        }).catch(function (err) {
        })
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate: function (row, index, done, loading) {
        if (this.location) {
          row.shopLongitude = String(this.location.lng)
          row.shopLatitude = String(this.location.lat)
        }
        row.openingHours = row.shopHours[0].getTime()
        row.closingHours = row.shopHours[1].getTime()
        delete row.shopHours;
        delete row.map;
        putObj(row).then(data => {
          this.tableData.splice(index, 1, Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          done()
          this.getList(this.page, {'id': this.shopId})
        }).catch(ex => {
          loading()
        })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave: function (row, done, loading) {
        if (!this.location) {
          this.$message({
            message: '请选择服务范围中心',
            type: 'error'
          })
          return false
        }
        row.shopLongitude = String(this.location.lng)
        row.shopLatitude = String(this.location.lat)
        row.openingHours = row.shopHours[0].getTime()
        row.closingHours = row.shopHours[1].getTime()
        delete row.shopHours;
        delete row.map;
        addObj(row).then(data => {
          this.tableData.push(Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
          done()
          this.getList(this.page, {'id': this.shopId})
        }).catch(ex => {
          loading()
        })
      },
      /**
       * 刷新回调
       */
      refreshChange() {
        this.getList(this.page, {'id': this.shopId})
      },
      // 打开服务类型弹窗
      handleOpenSerTypeDialog(row, index) {
        this.currentShopId = row.id
        let _this = this
        //获取商铺与服务类型关联数据
        allMerServiceTypes()
          .then(res => {
            _this.typeIds = res.data.data
            _this.serTypeDialogVisible = true
          }).then(() => {
          getShopSerTypeObjByShopId(row.id)
            .then(res => {
              this.typeIdListChecked = []
              for (let i = 0; i < res.data.data.length; i++) {
                for (let j = 0; j < _this.typeIds.length; j++) {
                  if (res.data.data[i].typeId == _this.typeIds[j].id) {
                    this.typeIdListChecked.push(Number(res.data.data[i].typeId))
                  }
                }
              }

            })
        })

      },
      //
      handleCheckedTypeIdChange(value) {
        if (!value || value.length <= 0) {
          this.$message.error('至少有一个服务类型')
          return false
        }
        let data = new FormData()
        data.append('shopId', this.currentShopId)
        data.append('typeIds', value)
        saveShopSerTypes(data)
          .then(res => {

          })
      },
      handleCheckedMerUserChange(value) {
        let data = new FormData()
        data.append('shopId', this.currentShopId);
        data.append('userIds', value)
        addShopUserObj(data)

          .then(res => {
            if (res.data.code === 0) {
              this.$message.success('添加成功')
            } else {
              this.$message.error('添加失败')
            }
          })
      },
      formatWith6digts(obj) {
        var p1 = /[^\d\.]/g;	// 过滤非数字及小数点 /g :所有范围中过滤
        var p2 = /(\.\d{6})\d*$/g;
        var p4 = /(\.)(\d*)\1/g;
        obj.value = obj.value.replace(p1, "").replace(p2, "$1").replace(p4, "$1$2");


        obj.value = obj.value.replace(/[^0-9.]/g, '');


        // fix bug: many char'.'
        var p5 = /\.+/g;	//多个点的话只取1个点，屏蔽1....234的情况
        obj.value = obj.value.replace(p5, ".")

        var p6 = /(\.+)(\d+)(\.+)/g; //屏蔽1....234.的情况
        obj.value = obj.value.replace(p6, "$1$2")// 屏蔽最后一位的.
        // end fix bug: many char'.'
      },
      getLocation(e) {
        this.location = e
        // console.log(this.location)
        //  经度
        this.form.shopLatitude = this.location.lat
        // 纬度
        this.form.shopLongitude = this.location.lng
      },
      searchChange(params) {
        this.getList(this.page, params)
      },
      handleGeneratingCode(row, index) {
        let data = new FormData()
        data.append('shopId', row.id)
        generatingCouponCode(data)
          .then(res => {
            this.getList(this.page, {'id': this.shopId})
          })
      },
      currentChange(val) {
        this.page.currentPage = val
        this.getList(this.page)
      },
      sizeChange(val) {
        this.page.currentPage = 1
        this.page.pageSize = val
        this.getList(this.page)
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
